package com.briup.jdbc;

import org.junit.Rule;
import org.junit.Test;

import java.sql.*;

/**
 * 使用jdbc完成DDL语句的使用
 * 删除表t_user
 * 创建表t_user
 */
public class DDLTest {
    public static final String driver = "com.mysql.cj.jdbc.Driver";
    public static final String url = "jdbc:mysql:///db01";
    public static final String username = "root";
    public static final String password = "rootroot";


    @Test
    public void dropTable(){
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,username,password);
            // 创建语句对象
            statement = connection.createStatement();
            // 准备sql语句
            String sql = "drop table t_user";
            // 执行DDL的sql语句
            int i = statement.executeUpdate(sql);
            System.out.println("i = " + i);
            System.out.println("删除表成功");

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if(statement!=null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    @Test
    public void createTable(){
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,username,password);
            // 创建语句对象
            statement = connection.createStatement();
            // 准备sql语句
            String sql = "create table t_user("
                    + "id int primary key,"
                    + "name varchar(50) not null,"
                    + "age int"
                    + ")";
            // 执行DDL的sql语句
            int i = statement.executeUpdate(sql);
            System.out.println("i = " + i);
            System.out.println("创建表成功");

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if(statement!=null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
